package com.hyh.admin.controller.resources;

import com.alibaba.fastjson.JSON;
import com.hyh.ad.common.annotation.Log;
import com.hyh.ad.common.core.controller.BaseController;
import com.hyh.ad.common.core.domain.AjaxResult;
import com.hyh.ad.common.core.page.TableDataInfo;
import com.hyh.ad.common.enums.BusinessType;
import com.hyh.ad.common.utils.SecurityUtils;
import com.hyh.admin.domain.resources.Resources;

import com.hyh.admin.domain.resources.vo.ResourcesCategoryVo;
import com.hyh.admin.domain.resources.vo.ResourcesVo;
import com.hyh.admin.recommend.ScoreCalculatorService;
import com.hyh.admin.recommend.UserProfile;
import com.hyh.admin.recommend.UserProfileService;
import com.hyh.admin.service.IResourcesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/resources")
@Api(tags = "资源管理")
public class ResourcesController extends BaseController {
    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private ScoreCalculatorService scoreCalculatorService;

    /*
     * 查询资源列表-根据热度查询
     */
    @GetMapping("/list/hot")
    @ApiOperation(value = "资源列表-根据热度查询")
    public AjaxResult list(Resources resources) {
        return AjaxResult.success(resourcesService.selectResourcesByHot(resources));
    }

    /*
     * 查询资源列表-根据用户id
     */
    @GetMapping("/list/{userId}")
    @ApiOperation(value = "资源列表-根据用户id")
    public AjaxResult listByUserId(@PathVariable Long userId) {
        return AjaxResult.success(resourcesService.selectResourcesByUserId(userId));
    }

    /*
     * 查询资源详情-根据资源id
     */
    @GetMapping("/get/{id}")
    @ApiOperation(value = "资源详情-根据资源id")
    public AjaxResult get(@PathVariable Long id) {
        //获取用户画像
        UserProfile userProfile = userProfileService.getUserProfile(SecurityUtils.getLoginUser().getUser().getId().toString());
        scoreCalculatorService.updateCourseScore(userProfile,id.toString(),"clicked");
        return AjaxResult.success(resourcesService.selectResourcesById(id));
    }


    /*
     * 根据父类id查询资源列表
     */
    @GetMapping("/list/parent/{parentId}")
    @ApiOperation(value = "资源列表-根据父类id查询资源列表")
    public AjaxResult listByParentId(@PathVariable Long parentId) {
        return AjaxResult.success(resourcesService.selectResourcesByParentId(parentId));
    }
    /*
     * 新增资源
     */
    @PostMapping("/insert")
    @ApiOperation(value = "新增资源")
    @PreAuthorize("hasAnyAuthority('sys:admin:permission','sys:crud:course')")
    @Log(businessName = BusinessType.INSERT, operationModule = "新增课程")
    public AjaxResult insert(Resources resources) {
        return AjaxResult.success(resourcesService.insertResources(resources));
    }

    /*
     * 更新资源
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新资源")
    public AjaxResult update(Resources resources) {
        return AjaxResult.success(resourcesService.updateResources(resources));
    }

    /*
     * 删除资源
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除资源")
    @PreAuthorize("hasAnyAuthority('sys:admin:permission','sys:crud:course')")
    @Log(businessName = BusinessType.DELETE, operationModule = "删除课程")
    public AjaxResult delete(Resources resources) {
        return AjaxResult.success(resourcesService.deleteResources(resources));
    }

    /*
     * 批量删除资源
     */
    @DeleteMapping("/delete/batch/{ids}")
    @ApiOperation(value = "批量删除资源")
    @PreAuthorize("hasAnyAuthority('sys:admin:permission','sys:crud:course')")
    @Log(businessName = BusinessType.DELETE, operationModule = "删除课程")
    public AjaxResult deleteBatch(@PathVariable Long[] ids) {
        return AjaxResult.success(resourcesService.deleteResourcesBatch(ids));
    }

    /*
     * 查询资源列表-根据分类id
     */
    @GetMapping("/list/category/{categoryId}")
    @ApiOperation(value = "资源列表-根据分类id")
    public AjaxResult listByCategoryId(@PathVariable Long categoryId) {
        return AjaxResult.success(resourcesService.selectResourcesByCategoryId(categoryId));
    }

    /*
     * 查询资源列表-所有资源
     */
    @GetMapping("/list")
    @ApiOperation(value = "资源列表-所有资源")
    public TableDataInfo list() {
        startPage();
        return getDataTable(resourcesService.selectResourcesList());
    }

    /*
     * 查询资源列表-所有资源
     */
    @GetMapping("/list/page")
    @ApiOperation(value = "资源列表-所有资源-自定义")
    @PreAuthorize("hasAnyAuthority('sys:admin:permission','sys:crud:course')")
    public TableDataInfo listPage(Resources resources) {
        startPage();
        return getDataTable(resourcesService.selectResourcesListPage(resources));
    }


    /*
     * 更改审核状态
     */
    @GetMapping("/updateStatus/{id}")
    @ApiOperation(value = "更改课程状态")
    @PreAuthorize("hasAnyAuthority('sys:admin:permission','sys:crud:course')")
    @Log(businessName = BusinessType.UPDATE, operationModule = "审核课程")
    public AjaxResult updateStatus(@PathVariable Long id ,@Param("status") String status) {
        return AjaxResult.success(resourcesService.updateStatus(id,status));
    }

    /*
     * 点赞
     */
    @PutMapping("/like/{id}")
    @ApiOperation(value = "点赞")
    public AjaxResult like(@PathVariable Long id) {
        Resources resources = resourcesService.selectResourcesById(id);
        resources.setLoveCount(Integer.parseInt(resources.getLoveCount()) + 1 + "");
        return toAjax(resourcesService.updateResources(resources));
    }

    /*
     * 增加播放量
     */
    @PutMapping("/playHot/{id}")
    @ApiOperation(value = "增加播放量")
    public AjaxResult playHot(@PathVariable Long id) {
        Resources resources = resourcesService.selectResourcesById(id);
        resources.setHotDegree(Integer.parseInt(resources.getHotDegree()) + 1 + "");
        return toAjax(resourcesService.updateResources(resources));
    }

    /*
     * 批量导入数据到es
     */
    @GetMapping("/addEsProduct")
    @ApiOperation(value = "批量导入数据到es")
    public AjaxResult addEsProduct() {
        // 创建一个批量请求对象
        BulkRequest bulkRequest = new BulkRequest();

        // 获取所有需要导入的数据
        List<ResourcesCategoryVo> resourcesCategoryVos = resourcesService.selectResourcesList();

        // 将每条资源数据添加到批量请求中
        for (ResourcesCategoryVo resourcesCategoryVo : resourcesCategoryVos) {

            ResourcesVo resourcesVo = new ResourcesVo(resourcesCategoryVo);
            String json = JSON.toJSONString(resourcesVo);

            // 为每个资源创建一个 IndexRequest，并将其添加到批量请求中
            bulkRequest.add(new IndexRequest("resources")
                    .id(resourcesVo.getId().toString())
                    .source(json, XContentType.JSON));
        }

        try {
            // 在循环外部执行批量操作
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
            return AjaxResult.success();
        } catch (IOException e) {
            // 捕获异常并抛出 RuntimeException
            throw new RuntimeException(e);
        }
    }


    /*
     * 上传课程资源
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传课程资源 -- 上传封面图片和视频 标题 描述 分类 标签")
    public AjaxResult uploadResource(
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("categoryId") Long categoryId,
            @RequestParam("tags") String tags,
            @RequestParam("coverImage") MultipartFile coverImage,
            @RequestParam(value = "parentId", required = false) Long parentId,
            @RequestParam("video") MultipartFile video) {

        // 处理上传
        Resources resource = resourcesService.saveResource(parentId,title, description, categoryId, tags, coverImage, video);

        // 返回响应
        Map<String, Object> response = new HashMap<>();
        addEsProduct();
        response.put("message", "上传成功");
        response.put("resource", resource);

        return AjaxResult.success(response);
    }

    /*
     * 查询我的课程
     */
    @GetMapping("/my")
    @ApiOperation(value = "查询我的课程")
    public TableDataInfo my() {
        startPage();
        return getDataTable(resourcesService.selectResourcesByUserId(SecurityUtils.getLoginUser().getUser().getId()));
    }


    /*
     * 获取用户画像
     */
    @GetMapping("/userProfile")
    @ApiOperation(value = "获取用户画像 测试使用")
    public AjaxResult userProfile() {
        return AjaxResult.success(userProfileService.getUserProfile(SecurityUtils.getLoginUser().getUser().getId().toString()));
    }


    /*
     * 获取词云
     */
    @GetMapping("/wordCloud")
    @ApiOperation(value = "获取词云")
    public AjaxResult wordCloud(Resources resources) {
        return AjaxResult.success(resourcesService.selectResourcesWordList(resources));
    }

    /*
     * 获取资源统计习惯
     */
    @GetMapping("/statistics")
    @ApiOperation(value = "获取资源统计记录")
    public AjaxResult statistics(Resources resources) {
        return AjaxResult.success(resourcesService.selectResourcesLearnList(resources));
    }
}